#include "factory.h"

int train_file(int new_fd)
{
    // 发送文件名
    train_t t;
    t.data_len = strlen(FILENAME);
    strcpy(t.buf, FILENAME);
    int ret = send_n(new_fd, &t, 4 + t.data_len);
    SELFFUNC_ERR_CHECK(ret, "send_n");

    // 发送文件大小
    struct stat file_info;
    stat(FILENAME, &file_info);
    t.data_len = sizeof(file_info.st_size);
    memcpy(t.buf, &file_info.st_size, sizeof(file_info.st_size));
    ret = send_n(new_fd, &t, 4 + t.data_len);
    SELFFUNC_ERR_CHECK(ret, "send_n");

    // 发送文件内容
    int fd = open(FILENAME, O_RDONLY);
    while (t.data_len = read(fd, t.buf, sizeof(t.buf)))
    {
        ret = send_n(new_fd, &t, 4 + t.data_len); // 大文件使用循环发送
        SELFFUNC_ERR_CHECK(ret, "send_n");
    }
    // 发送文件结束符
    t.data_len = 0;
    ret = send_n(new_fd, &t, 4 + t.data_len);
    SELFFUNC_ERR_CHECK(ret, "send_n");
}

int recv_n(int sfd, void* buf, int data_len)
{
    char *p = (char *)buf;
    int total = 0, ret;

    while (total < data_len)
    {
        ret = recv(sfd, p + total, data_len - total, 0);
        if (ret == 0) // 服务器断开
        {
            return -1;
        }
        total += ret;
    }
    return 0;
}

int send_n(int sfd, void* buf, int data_len)
{
    char *p = (char *)buf;
    int total = 0, ret;

    while (total < data_len)
    {
        ret = send(sfd, p + total, data_len - total, 0);
        if (ret == -1) // 客户端断开
        {
            return -1;
        }
        total += ret;
    }
    return 0;
}
